<template>
  <el-dialog title="分配角色" v-model="visible" width="30%" @closed="closed">
    <el-select v-model="allocRoleIds" multiple placeholder="请选择" size="small" style="width: 80%">
      <el-option v-for="item in allRoleList" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAllocDialogConfirm" size="small">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { allocRole, getRoleByAdmin } from '@/api/user'
import { fetchAllRoleList } from '@/api/role'
import type { Role } from '@/models/role'

const visible = ref(false)
const allocRoleIds = ref<number[]>([])
const allRoleList = ref<Role[]>([])
const allocAdminId = ref<number>()

async function handleAllocDialogConfirm() {
  let params = {
    adminId: allocAdminId.value as number,
    roleIds: allocRoleIds.value.join(','),
  }
  await allocRole(params)
  ElMessage.success('分配成功！')
  visible.value = false
}
async function getRoleListByAdmin(adminId: number) {
  const res = await getRoleByAdmin(adminId)
  const list = res.data.data || []
  allocRoleIds.value = list.map((item) => item.id as number)
}

async function getAllRoleList() {
  const res = await fetchAllRoleList()
  allRoleList.value = res.data.data
}

const closed = () => {
  allocRoleIds.value = []
  allocAdminId.value = undefined
}

const show = (id: number) => {
  allocAdminId.value = id
  visible.value = true
  id && getRoleListByAdmin(id)
}

getAllRoleList()
defineExpose({ show })
</script>

<style scoped></style>
